#!/usr/bin/python
import sys
import os
import time

# Check for input argument
if len(sys.argv)<2:
	print "not enough arguments \n enter: resource_splitter.py [source path]"

else:

	# Open input file
	inputFile=open(sys.argv[1],"r")
	
	# Determine if this is consolidation mode
	consolidate = False
	if((len(sys.argv) == 3) and (sys.argv[2] == '-c')):
		consolidate = True
	
	# Create the log directory
	logDir = "parsed_logs_" 
	if(consolidate == True):
		logDir += "consolidated_"
	logDir += str(time.time())
	os.makedirs(logDir)
	
	# Add a prefix to the log directory if this is *nix
	logDirPrefix = '';
	if sys.platform!='win32':
		logDirPrefix += './'
	
	# Open cpu and mem  output files
	outputFile_cpu = open(logDirPrefix + logDir + '/cpu.log',"w")
	outputFile_memory = open(logDirPrefix + logDir + '/memory.log',"w")
	outputFile_free_mem = open(logDirPrefix + logDir + '/free_mem.log',"w")

	# Open net output file(s)
	outputFile_net_in = None
	outputFile_net_out = None
	outputFile_net = None	
	if(consolidate == True):
		outputFile_net = open(logDirPrefix + logDir + '/net.log',"w")
	else:
		outputFile_net_in = open(logDirPrefix + logDir + '/net_in.log',"w")
		outputFile_net_out = open(logDirPrefix + logDir + '/net_out.log',"w")
	
	# Open disk output file(s)
	outputFile_disk_read = None
	outputFile_disk_write = None
	outputFile_disk = None	
	if(consolidate == True):
		outputFile_disk = open(logDirPrefix + logDir + '/disk.log',"w")
	else:	
		outputFile_disk_read = open(logDirPrefix + logDir + '/disk_read.log',"w")
		outputFile_disk_write = open(logDirPrefix + logDir + '/disk_write.log',"w")
	
	# Read in everything
	i = 0
	inputLines = inputFile.readlines()
	while i<len(inputLines):
	
		# Tokenize
		inputChunks = inputLines[i].split('|')
		
		# Parse and write cpu, mem and vbd
		outputFile_cpu.write(inputChunks[4]+"\n")
		outputFile_memory.write(inputChunks[5]+"\n")
		outputFile_free_mem.write(inputChunks[6]+"\n")
		
		# Parse and write net
		if(consolidate == True):
			outputFile_net.write(str(int(inputChunks[7]) + int(inputChunks[8]))+"\n")
		else:
			outputFile_net_in.write(inputChunks[7]+"\n")
			outputFile_net_out.write(inputChunks[8]+"\n")
		
		# Parse and write disk
		if(consolidate == True):
			outputFile_disk.write(str(int(inputChunks[10]) + int(inputChunks[11].strip()))+"\n")
		else:
			outputFile_disk_read.write(inputChunks[10]+"\n")
			outputFile_disk_write.write(inputChunks[11].strip()+"\n")
		
		# Increment counter
		i += 1
	
	# Print that we're finished
	print "Done, wrote to folder " + logDir

